<?php
/*********************************************************************************************************************
avail.php

usage:				avail.php is used in conjunction with an ajax call using the http post method to get the availability of the 
							team members sent in via the QMAIL parameter during the date range established by the STARTDATE and ENDDATE parameters
 							
required params: 
	qmail:			email addresses of the team members that need to be queried in the database separated with the | (pipe) character 
	start: 	date in the format: yyyy-mm-ddThh:mm:ss that represents the begining of the time interval to search
	end:		date in the format: yyyy-mm-ddThh:mm:ss that represents the end of the time interval to search
	interval: 	establishes the period of time that is represented by each 2 bits in the returned bit string

returns a string representing the availability of team member with each member's schedule separated by a \n (newline) charcter 
using the following scheme:
								0 - user is avail for that interval
								1 - user is mildly busy during that interval
								2 - user is unavailable for that interval

*********************************************************************************************************************/	
	require_once "dBConnect.php";
	require_once "events.php";
	$db = new dBConnect();
	$startDate = strtotime($_POST['start']);
	$endDate = strtotime($_POST['end']);
	$qmail = split("\|", $_POST['qmail']);
	//$interval = $_POST['interval'];
	$interval = ($endDate - $startDate)/12;
	
	/*Test data*/
	/*$qmail = split("\|", "juan@padillatech.com");
	$startDate = strtotime("2008-05-05T12:00:00");
	$endDate = strtotime("2008-05-05T22:00");
	$interval = 3600;*/
	/*end Test data*/
	$rtn = "";
	foreach($qmail as $mail){
			$token_resp = $db->getData("authsub", "users", "email='$mail'");
		
			//create a client
			$client = Zend_Gdata_Authsub::getHttpClient($token_resp[0]['authsub']);
			//get events
			$events = outputCalendarByDateRange($client, $startDate, $endDate);
			//need to go through the events that Google has sent and parse the avail times
			
			$counter = $startDate;
			foreach($events as $event){
				foreach($event->when as $when){//echo "st: ".$when->startTime."<br/>";
					$d = split(" ", $when);
					$evStart = strtotime($d[1]);
					$evEnd = strtotime($d[3]);
					
					while($counter < $evStart && $evStart >= ($counter + $interval) && $counter < $evEnd && $counter < $endDate){
						$counter += $interval;
						$rtn .= "0";
					}
					while($counter < $evEnd && $counter < $endDate){
						$counter += $interval;
						$rtn .= "2";
					}
				}
			}
			
			while($counter < $endDate){
					$counter += $interval;
					$rtn .= "0";
			}	
			$rtn .= "|";
	}
	
	echo trim($rtn, "|");
	
?>